package com.jdew.thkj.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.view.ClipViewLayout;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import butterknife.Bind;

/**
 * Created by yangyang on 2017/5/17.
 */

public class ClipImageActivity extends BaseActivity {

    @Bind(R.id.clipViewLayout1)
    ClipViewLayout clipViewLayout1;
    @Bind(R.id.clip_cancel)
    TextView clip_cancel;
    @Bind(R.id.clip_ok)
    TextView clip_ok;

    @Override
    public int bindLayout() {
        return R.layout.activity_clip_image;
    }

    @Override
    public void initView(View view) {
        clipViewLayout1 = (ClipViewLayout) view.findViewById(R.id.clipViewLayout1);
        clipViewLayout1.setImageSrc(getIntent().getData());
        clip_cancel.setOnClickListener(this);
        clip_ok.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * 生成Uri并且通过setResult返回给打开的activity
     */
    private void generateUriAndReturn() {
        //调用返回剪切图
        Bitmap zoomedCropBitmap;
        zoomedCropBitmap = clipViewLayout1.clip();
        if (zoomedCropBitmap == null) {
            Log.e("android", "zoomedCropBitmap == null");
            return;
        }
        Uri mSaveUri = Uri.fromFile(new File(getCacheDir(), "cropped_" + System.currentTimeMillis() + ".jpg"));
        if (mSaveUri != null) {
            OutputStream outputStream = null;
            try {
                outputStream = getContentResolver().openOutputStream(mSaveUri);
                if (outputStream != null) {
                    zoomedCropBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                }
            } catch (IOException ex) {
                Log.e("android", "Cannot open file: " + mSaveUri, ex);
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            Intent intent = new Intent();
            intent.setData(mSaveUri);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.clip_cancel:
                finish();
                break;
            case R.id.clip_ok:
                generateUriAndReturn();
                break;
            default:
                break;
        }

    }

}
